<?php
namespace Cyfy\Modules\Users;

use \Cyfy\Message;

class Current extends \Cyfy\Translatable
{
    /**
     * IDs of groups the user is in.
     *
     * Default is 3 - Anonymous users.
     * @var array
     */
    static public $groups = array(3);
    
    /**
     * Permissions that user has.
     * @var array
     */
    static private $permissions = array();

    /**
     * User ID
     * @var int
     */
    static public $uid = 0;
    
    /**
     * User full name
     * @var string
     */
    static public $name = '';

    /**
     * User username
     * @var string
     */
    static public $username = '';

    /**
     * User password hash
     * @var string
     */
    static public $password = '';

    /**
     * User original password
     * @var string
     */
    static private $passwordOriginal = '';
    
    /**
     * User email
     * @var string
     */
    static public $email = '';
    
    /**
     * User last login
     * @var string
     */
    static public $lastLogin;

    /** 
     * Returns true, if user has permissions.
     * @return bool
     */
    static function hasPermission($module, $permission)
    {
        // if user in administrators -> true
        if(in_array(1, self :: $groups))
        {
            return true;
        }
        
        // else
        return (self :: $permissions[$module][$permission] == true) ? true : false;
    }
    
    /** 
     * Adds permission to the user.
     * @return bool
     */
    static private function addPermission($module, $permission)
    {
        return self :: $permissions[$module][$permission] = true;
    }

    
    /**
     * Loads in the user.
     *
     * @param array Associative array in format of:
     * <code>
     * array('username'=>'root', 'password' => '****');
     * </code>
     * @return bool TRUE, if user logged in.
     */
    static public function load($data)
    {
        // empty array
        if ($data == array()) {
            return false;
        }
        // crops the array
        $data = array('username' => $data['username'], 'password' => $data['password']);
        
        // sets original pass
        self :: $passwordOriginal = $data["password"];

        $data["password"] = Module :: hashPassword($data["password"]);
        // fetch data
        $result = \dibi :: query("SELECT * FROM [:cyfy:Users-users] WHERE %and", $data);
        if(count($result) == 0)
        {
            \Cyfy\Log :: write("User {$data["username"]} with password hash {$data["password"]} failed to log in.");
            return false;
        }
        
        // found
        $user = $result -> fetch();
        // loads the data
        foreach ($user as $code => $value) {
            self :: $$code = $value;
        }
        
        // logged group
        self :: $groups[] = 2;
        // loads the groups
        $result = \dibi :: query("SELECT [gid] FROM [:cyfy:Users-users-groups] WHERE uid = %i", self :: $uid);
        foreach($result as $g)
        {
            self :: $groups[] = $g['gid'];
        }
        
        \Cyfy\Log :: write("User {$data["username"]} loaded.");
        return true;
    }
    
    /**
     * Loads permissions for the Current user.
     */
    static public function loadPermissions()
    {
        // load permissions for user
        $result = \dibi :: query("SELECT [module], [permission] FROM [:cyfy:Users-groups-permissions] WHERE [gid] IN (%in)", Current :: $groups);
        foreach($result as $gp)
        {
            self :: addPermission($gp["module"], $gp["permission"]);
        }    
    }

    /**
     * Logs in the user. Uses the function User::load() and shows messages.
     *
     * @param string    Username
     * @param string    Not hashed password
     * @return bool
     */
    static public function login($username, $password)
    {
        $load = self :: load(array("username" => $username, "password" => $password));
        if ($load == true)
        {
            \dibi :: query("UPDATE [:cyfy:Users-users] SET [lastLogin] = %t WHERE uid = " . self::$uid . "", new \DateTime());
            \Cyfy\Message :: set(self :: t(130));
            return true;
        }
        \Cyfy\Message :: set(self :: t(120), \Cyfy\Message :: ERROR);
        return false;
    }

    /**
     * Logs out the user from the current session and redirects user to INDEX.
     * @return string
     */
    static public function logout()
    {
        $output = "<h2>" . self :: t(200) . "</h2>\n";
        if (self :: $uid != 0)
        {
            // User logged
            unset($_SESSION["userS"]);
            self :: $uid = 0;
            \Cyfy\Message :: set(self :: t(210));
            \Cyfy\Cyfy ::  redirectTo("");
        }
        else
        {
            // User not logged
            $output .= \Cyfy\Message :: get(self :: t(220), \Cyfy\Message::WARNING);
        }
        return $output;
    }
    
    /**
     * Saves current user session.
     * @return bool
     */
    static public function saveSession()
    {
        if(Current :: $uid != 0)
        {
            \Cyfy\Log :: write('User session saved.');
            $_SESSION['userS'] = array('username' => Current :: $username, 'password' => Current :: $passwordOriginal);
            return true;
        }
        return false;
    }
    
    
    /**
     * Settings for current user.
     * @return string HTML content.
     */
    static public function settings()
    {
        if(self :: $uid == 0)
        {
            \Cyfy\Cyfy ::  noPermission();
            return false;
        }
        
        // loads data for
        $user = User :: load(self :: $uid);

        // creates a new form
        $form = new Forms\Settings();
        $form->setData($user -> info);

        // account settings
        $output = "<h2>" . self :: t(510) . "</h2>";
        $output .= $form -> show();

        // profile??
        if(\Cyfy\Modules :: isEnabled("Profile"))
        {
            $output .= \Cyfy\Modules\Profile\Profile :: settings(self :: $uid);
        }

        return $output;
    }
}

